
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config.default');
const { tokenExpiredError, invalidToken, hasNotAdminPermission } = require('../constant/err.type');
const { errorRequest } = require('../utils/util');

// jwt鉴权
const auth = async (ctx, next) => {
  try {
    const { authorization = '' } = ctx.request.header;
    const token = authorization.replace('Bearer ', '');
    // jwt.verify 使用指定的密钥对JWT进行验证，并返回解密后的payload
    const userInfo = jwt.verify(token, JWT_SECRET);
    // 写入全局 user  
    ctx.state.user = userInfo;
  } catch (err) {
    switch (err.name) {
      case 'TokenExpiredError':
        return errorRequest(ctx, tokenExpiredError, err);
      case 'JsonWebTokenError':
        return errorRequest(ctx, invalidToken, err);
    }
  }
  await next();
}

// 用户权限管理
const hadAdminPermission = async (ctx, next) => {
  const { is_admin, user_name } = ctx.state.user;
  if (!is_admin) {
    return errorRequest(ctx, hasNotAdminPermission, `当前用户没有管理员权限 ${user_name}`);
  }
  await next();
}

module.exports = {
  auth,
  hadAdminPermission
}